package uno.linze.wallpaper.domain.identity.service.ext;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import uno.linze.wallpaper.domain.identity.entity.Users;
import uno.linze.wallpaper.domain.identity.repository.UserResponsitory;

import java.security.Key;
import java.util.Date;

@Service
public class AuthService {

    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);

    private final UserResponsitory userResponsitory;
    private final PasswordEncoder passwordEncoder;
    private final Key jwtSecretKey;
    private final long jwtExpirationMs;

    public AuthService(UserResponsitory userResponsitory,
                       PasswordEncoder passwordEncoder,
                       @Value("${app.jwt.expiration-ms}") long expirationMs) {
        this.userResponsitory = userResponsitory;
        this.passwordEncoder = passwordEncoder;
        // 使用安全的自动生成密钥，确保满足HS512算法要求
        this.jwtSecretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);
        this.jwtExpirationMs = expirationMs;
        logger.info("JWT密钥已安全生成，满足HS512算法要求");
    }

    /**
     * 用户登录并生成JWT
     * @param username 用户名
     * @param password 密码
     * @return JWT Token, 如果验证失败则返回 null
     */
    public String loginAndGenerateToken(String username, String password) {
        // 1. 从仓库获取用户信息 (注意：login方法此时只用于按��户名查找)
        Users user = userResponsitory.login(username, password);

        if (user == null) {
            // 用户不存在
            logger.warn("登录失败：用户 '{}' 不存在。", username);
            return null;
        }

        // 2. 验证密码
        if (!passwordEncoder.matches(password, user.getPasswordHash())) {
            // 密码不匹配
            logger.warn("登录失败：用户 '{}' 的密码不匹配。", username);
            return null;
        }

        // 3. 生成JWT
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
                .signWith(jwtSecretKey, SignatureAlgorithm.HS512)
                .compact();
    }

    /**
     * 验证JWT并从中获取用户名
     * @param token JWT
     * @return 如果token有效，则返回用户名，否则返回null
     */
    public String validateTokenAndGetUsername(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(jwtSecretKey)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims.getSubject();
        } catch (io.jsonwebtoken.security.SignatureException e) {
            logger.error("无效的JWT签名: {}", e.getMessage());
        } catch (MalformedJwtException e) {
            logger.error("无效的JWT令牌: {}", e.getMessage());
        } catch (ExpiredJwtException e) {
            logger.error("JWT令牌已过期: {}", e.getMessage());
        } catch (UnsupportedJwtException e) {
            logger.error("不支持的JWT令牌: {}", e.getMessage());
        } catch (IllegalArgumentException e) {
            logger.error("JWT claims字符串为空: {}", e.getMessage());
        }
        return null;
    }
}